<?php

namespace app\command\controller;

use app\common\func\Lib;
use app\common\func\Tools;
use app\common\func\Transaction;
use app\common\model\StandardMoney;
use app\common\model\transaction\Xyf;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;
use think\Log;

class Order extends Controller
{

    //商户绑定通知
    public function binds()
    {
        $data = request()->param("data");

        echo "S";

        $equip = Lib::getEquip($data['devId']);
        if($equip){
            $equip->binding_time = strtotime($data['operateTime']);
            $equip->save();
            //减少调拨机构库存
            Tools::updateStocks($equip->main_type, $equip->main_id, $equip->product_id, 2, [$data['devId']], "设备绑定减少库存");
        }else{
            file_put_contents("bind_log.txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
            file_put_contents("bind_log.txt","info:设备".$data['devId']."未找到".PHP_EOL,FILE_APPEND | LOCK_EX);
        }
    }

    //订单通知
    public function index()
    {
        $param = file_get_contents("php://input");
//        $param = "data%5BdevId%5D=223010095000004904054&data%5BagentId%5D=410043502667888&data%5BtransTime%5D=20230221160730&data%5BmerchName%5D=%E6%AD%A6%E5%9B%BD%E6%AD%A3&data%5BgatherType%5D=VIP&data%5BcardType%5D=C&data%5BposMerName%5D=%E8%B5%9B%E7%BD%95%E5%8C%BA%E9%83%AD%E8%8D%A3%E7%94%9F%E8%82%89%E5%BA%97&data%5BtransStat%5D=S&data%5BbagentId%5D=410043350052530&data%5BisActive%5D=1&data%5BordId%5D=20230221A055480129&data%5BcardNo%5D=622168%2A%2A%2A%2A%2A%2A5621&data%5BfeeAmt%5D=0.60&data%5BmerchId%5D=410043606751588&data%5BisSim%5D=0&data%5BtransType%5D=CARDPAY&data%5BtransAmt%5D=100.00&data%5BtransDate%5D=20230221&data%5BactAmt%5D=0.00&data%5BsettleType%5D=0";
//        file_put_contents("get_data.txt","data:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
        parse_str(urldecode($param), $res);
        if(!isset($res["data"])){
            echo "F";
            exit;
        }
        $data = $res["data"];
//        $data = [
//            "devId" => "hm0006",
//            "agentId" => "410043502667888",
//            "transTime" => "20230221160730",
//            "merchName" => "武国正",
//            "gatherType" => "VIP",
//            "cardType" => "C",
//            "posMerName" => "赛罕区郭荣生肉店",
//            "transStat" => "S",
//            "bagentId" => "410043350052530",
//            "isActive" => "1",
//            "ordId" => "20230221A055480129",
//            "cardNo" => "622168******5621",
//            "feeAmt" => "0.60",
//            "merchId" => "410043606751588",
//            "isSim" => "1",
//            "transType" => "CARDPAY",
//            "transAmt" => "100.00",
//            "transDate" => "20230221",
//            "actAmt" => "0.00",
//            "settleType" => "0"
//        ];

        try {
            $orderNum = $data['ordId'];
            $rate = ($data['feeAmt'] && $data['transAmt']) ? bcdiv((string)($data['feeAmt'] * 100),(string)$data['transAmt'],2) : 0;
            $merchantName = $data['merchName'];
            $tranAmount = $data['transAmt'];

            $obj = new Xyf();
            $obj->bagent_id = $data['bagentId'];
            $obj->agent_id = $data['agentId'];
            $obj->merchant_name = $data['merchName'];
            $obj->merchant_id = $data['merchId'];
            $obj->order_num = $orderNum;
            $obj->sn = $data['devId'];
            $obj->transaction_result = $data['transStat'];
            $obj->transaction_type = $data['transType'];
            $obj->gather_type = $data['gatherType'];
            $obj->settle__type = $data['settleType'];
            $obj->transaction_amount = $data['transAmt'];
            $obj->transaction_commission = $data['feeAmt'];
            $obj->transaction_rate = $rate;
            $obj->card_type = $data['cardType'];
            $obj->trading_time = strtotime($data['transTime']);
            $obj->card_num = $data['cardNo'];
            $obj->is_active = $data['isActive'];
            $obj->active_amt = isset($data['actAmt']) ? $data['actAmt'] : 0;
            $obj->is_flow = $data['isSim'];
            $obj->flow_amt = $data['isSim'] == 0 ? 0 : $data['simAmt'];
            $obj->save();

            echo "S";

            $sn = $data['devId'];
            $equip = Lib::getEquip($sn);
            if ($equip) {
                //判断设备激活
                $template = Lib::getProductTemplateByProduct($equip->product_id);
                $sum = Lib::getEquipTotalMoney($sn);
                if (!$equip->active_time && (time() - $equip->create_time) / (24 * 60 * 60) < $template->day_limit && $sum > $template->money) {
                    $equip->user_info = json_encode([
                        "merchant_name" => $data['merchName'],
                        "merchant_no" => $data['merchId']
                    ]);
                    $equip->active_time = time();
                    $equip->save();
                }

                //上级信息
                $level = Transaction::getRange($sn);
                if (count($level) > 0) {
                    $cashOrigin = 0;
                    $standardOrigin = 0;
                    $flowOrigin = 0;

                    if($equip->main_type == 1){
                        $companyId = $equip->main_id;
                    }else{
                        $user = Lib::getUserInfo($equip->main_id);
                        $companyId = $user->company_id;
                    }

                    foreach ($level as $key => $val) {
                        $policy = Lib::getPolicy($val['policy_id']);
                        //返现逻辑
                        if (Config::get("site.cash")) {
                            $cashMoney = Lib::getMoneyLog($val['type'], $val['id'], $sn, 2);
                            $cash = Lib::getCashById($policy->cash_id);
                            $moneyCash = $cash->reward - $cashOrigin;
                            $cashOrigin = $cash->reward;
                            if (!$cashMoney) {
                                if ($cash && $sum > $cash->money && $equip->active_time > 0 && (time() - $equip->active_time) / (24 * 60 * 60) < $cash->day_limit) {
                                    Tools::saveMoney($val['type'], $val['id'], 2, 1, $moneyCash, $sn,$equip->product_id,$companyId,"返现收益",["table_name" => "xyf","order_num" => $orderNum,"merchant_name" => $merchantName,"tran_amount" => $tranAmount]);
                                } else {
                                    break;
                                }
                            }
                        }

                        //达标逻辑
                        if (Config::get("site.standard")) {
                            $standards = Lib::getStandardByIds($policy->stardard_id);
                            foreach ($standards as $k => $v) {
                                if ($sum > $v->money && $equip->active_time > 0 && (time() - $equip->active_time) / (24 * 60 * 60) < $v->day_limit) {
                                    $money = $v->reward - $standardOrigin;//计算奖励金额,直属全给，跨级需要减去前一级的奖励金额
                                    $standardOrigin = $v->reward;
                                    $log = Lib::getStandardMoney($val['type'], $val['id'], $sn, $v->day_limit, $v->money);//查询是否给过对应奖励
                                    if (!$log) {
                                        Tools::saveMoney($val['type'], $val['id'], 4, 1, $money, $sn,$equip->product_id,$companyId, "达标收益",["table_name" => "xyf","order_num" => $orderNum,"merchant_name" => $merchantName,"tran_amount" => $tranAmount]);//修改余额

                                        //保存达标奖励记录
                                        $standardMoneyLog = new StandardMoney();
                                        $standardMoneyLog->main_type = $val['type'];
                                        $standardMoneyLog->main_id = $val['id'];
                                        $standardMoneyLog->sn = $sn;
                                        $standardMoneyLog->day_limit = $v->day_limit;
                                        $standardMoneyLog->money = $v->money;
                                        $standardMoneyLog->reward = $money;
                                        $standardMoneyLog->save();
                                    }
                                }
                            }
                        }

                        //流量卡逻辑
                        if (Config::get("site.flow")) {
                            if($data['isSim'] == 1){
                                $flowMoney = Lib::getMoneyLog($val['type'], $val['id'], $sn, 3);
                                $flow = Lib::getFlowById($policy->flow_id);
                                $moneyFlow = $flow->reward - $flowOrigin;
                                $flowOrigin = $flow->reward;
                                if (!$flowMoney) {
                                    Tools::saveMoney($val['type'], $val['id'], 3, 1, $moneyFlow, $sn,$equip->product_id,$companyId, "流量卡收益",["table_name" => "xyf","order_num" => $orderNum,"merchant_name" => $merchantName,"tran_amount" => $tranAmount]);
                                }
                            }
                        }
                    }
                }
            }

        }catch (\Exception $e){
            echo "F";
            file_put_contents("order_log.txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
            file_put_contents("order_log.txt","data:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            file_put_contents("order_log.txt","error:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
        }
    }

    //定时任务：处理订单，分润到账
    public function profit()
    {
        if (Config::get("site.rate")) {
            $list = Transaction::getDataList();
            foreach ($list as $key => $val) {
                if ($val->sn) {
                    $sn = $val->sn;

                    $equip = Lib::getEquip($sn);
                    if($equip->main_type == 1){
                        $companyId = $equip->main_id;
                    }else{
                        $user = Lib::getUserInfo($equip->main_id);
                        $companyId = $user->company_id;
                    }

                    $tranType = Lib::getTransactionTypeByCode($val->transaction_type);
                    $rate = Lib::getRateByName($val->transaction_rate);
//                    $cardTypeId = Transaction::getCardTypeId($val->card_type);
                    $cardTypeId = Tools::getCardTypeCode()[$val->card_type]['id'];
                    $channelId = Lib::getChannelByCode($val->gather_type);

                    if ($tranType && $rate && $cardTypeId && $channelId) {
                        //查询层级信息
                        $level = Transaction::getRange($sn);
                        if (count($level) > 0) {
                            $error = [];
                            $origin = 0;
                            foreach ($level as $k => $v) {
                                $policy = Lib::getPolicy($v["policy_id"]);
                                if ($policy) {
                                    $profitRate = Lib::getProfitDetailsByParams($policy->profit_id, $cardTypeId, $tranType->id, $rate->id,$channelId->id);
                                    if ($profitRate) {
                                        $money = Transaction::roundNumber($val->transaction_amount, $profitRate->profit_rate);
                                        Tools::saveMoney($v['type'], $v['id'], 1, 1, $money - $origin, $sn,$equip->product_id,$companyId, "分润收益",["table_name" => "xyf","order_num" => $val->order_num,"merchant_name" => $val->merchant_name,"tran_amount" => $val->transaction_amount]);
                                        $origin = $money;
                                    } else {
                                        $error[] = $val->card_type . $val->transaction_type . $val->transaction_rate . "未设置分润";
                                        break;
                                    }
                                } else {
                                    $error[] = "未找到政策：" . $v["policy_id"];
                                    break;
                                }
                            }
                            if (count($error) == 0) {
                                $val->process_state = 2;
                                $val->remark = "已处理";
                            } else {
                                $val->remark = implode(",", $error);
                            }
                        } else {
                            $val->remark = "未找到上级";
                        }
                    } else {
                        $val->remark = "不存在产品类型";
                    }
                } else {
                    $val->remark = "订单无设备号";
                }
                $val->save();
            }
        }
    }
}
